package comp3021.a1;

public class Counter extends Configuration{
	private ProductList purchasedList;
	float totalMoney; 
	float cash;
	Counter()
	{	
		System.out.printf("--------------------------------------------------------\n");
		System.out.printf("Welcome to the Electronic-Sales Counter! \n");
	}

	public void mode() 
	{
		do{
			  System.out.printf("Please enter '1' to record sales or '2' to exit: ");	
			  if(BatchOrInt ){
				  if(batch.hasNext())
				  {
				  input = batch.next();
				  System.out.println(input);
				  }
				  else	
					  {
					  logbook.error("No extra input");
					  System.exit(-1);
					  }
				  }
			  	else	input = userInput.next();
			}while(!isValidMode(input));
		welcome(Integer.parseInt(input));
	}
	
	boolean isValidMode(String s)
	{	
		int mode = 0;
		try{
			mode = Integer.parseInt(s);
			if(mode ==1 || mode ==2)	return true;
			else throw new Exception();		
		}
		catch(Exception illegalMode)
		{
			logbook.error("Invalid command ");
			if(BatchOrInt) System.exit(-1);
			return false;
		}
	}
	
	void welcome(int mode)
	{
			switch(mode){
			case 1:
				System.out.println("Please enter a list of purchasing-product ID and number");
				System.out.println("--------------------------------------------------------");
				recording();
				break;
			case 2:
				users.Logout();
				logbook.error("User"+ inputUser +" has successfully logged off!");
				break;		
			default:
				break;
				} 
	}
	void recording() {
		totalMoney = 0;			//initialize the variables
		cash = 0;
		purchasedList= new ProductList();
		NumOfSale+=1;		//After entering the recording, it will assign a number of purchased List.
		String id="";
		int productLocation ;
		while(true)
		{
			System.out.printf("Please enter product ID or press 'c' to end the list: ");
			
					if(BatchOrInt) 
					{
						if(batch.hasNext()){
							id = batch.next();
							System.out.println(id);
						}
						else
						{
							logbook.error("No extra data");
							System.exit(-1);
						}
					}
					else id = userInput.next();
			if(id.equals("c")) break;					//c == end the list
			productLocation= products.isExist(id);		//if item doesnt exist in product list, it will return -1, otherwise, it will return the index of productlist
			if(productLocation != -1){	
				recordItem(id, productLocation);
			}
			else
			{	
				if(BatchOrInt){
					logbook.error("Incorrect product ID!");
					System.exit(-1);
				}
				else{
					System.out.println("Product not exists!");
				}
			}
		}
		pay();
	}
 void recordItem(String id, int index) {
		String itemName;
		Product item;
		int number =0 ;
		itemName = products.itemName();
		System.out.printf("Product name is "+itemName+" , purchased number:");
		while(true)
		{
			try{
			if(BatchOrInt){
				if(batch.hasNext())
				{
				input = batch.next();
				System.out.println(input);
				}
				else
				{
					logbook.error("No extra data");
					System.exit(-1);
				}
				}
			else 	input= userInput.next();
			number = Integer.parseInt(input);
			if(number <0) throw new Exception();
			
			break;
		}
		catch(Exception IO){
   			if(BatchOrInt) {
   				logbook.error("Invalid Number!"); 
   				System.exit(-1);
   			}
   			else{
   				System.out.printf("Please enter a valid number: ");
   				continue;
   				}  			
   			}
		}
		
		item = new Product(id, itemName , products.howmuch(), number);
		if( ! purchasedList.alreadyAdd(item) )
		{		
            if( products.canBuy(index,number) )
            {
				purchasedList.plist.add(item);
            }
            else
            {
                    System.out.println("Not Enough Stock");
            } 
		}
		else
		{
			if(products.canBuy(index,number))
            {
			int deplicate = purchasedList.isExist(id);
			purchasedList.plist.get(deplicate).add( number );	
            } 
			else
            {
               System.out.println("Not Enough Stock");
            }
		}
		products.plist.get(index).update(number);		//update stock in our repository
	}
	 void pay() {
		System.out.println("--------------------------------------------------------");
		System.out.println("Purchasing-product list:");
		if(purchasedList.plist.size() < 1)	
		{
			System.out.println("No item on the List");
		}
		else
		{
			for(int i =0;i<purchasedList.plist.size();i++)
			{	
				float sumOfItem= 0;
				System.out.printf(purchasedList.plist.get(i).getName());
				System.out.printf(" * ");
				System.out.print(purchasedList.plist.get(i).howmany() );
				System.out.printf(" = ");
				sumOfItem = purchasedList.plist.get(i).howmuch() * purchasedList.plist.get(i).howmany();
				totalMoney+=sumOfItem;
				formattedFloat = myFormat.format(sumOfItem);
				System.out.println(" $"+formattedFloat);	
			}
			System.out.println("--------------------------------------------------------");
			System.out.printf("The Total price is ");
			System.out.println(" $"+totalMoney);
			System.out.printf("Please pay with cash, received cash (or cancel by entering '0')$: ");
			while(true)
			{
				try{
				if(BatchOrInt)		
				{
					if(batch.hasNext()){
						input= batch.next();
						System.out.println(input);
					}
					else{
						logbook.error("No Extra data");
						System.exit(-1);
					}
				}
				else 	input = userInput.next();
				cash = Float.parseFloat(input);
				if(cash < 0 ) throw new Exception();
				break;
				}
			catch(Exception IO){
	   			if(BatchOrInt)
	   			{
	   				System.out.println("Invalid cash");
	   			}
	   			else
	   			{
	   				System.out.printf("Please re-pay cash: ");
	   				continue;
	   			}

	   			}
			}
			
			if(cash == 0 )		//cancel the purchase
			{
			cancel(); 
			}
			else{
				if(cash < totalMoney )
				{	
					if(BatchOrInt)
						{
							logbook.error("Cash not enough!");	
							System.exit(-1);
						}
					else		
						{
						do{
							System.out.printf("Sorry,cash not enough, please enter cash amount again: ");
							while(true)
							{	
							
								try{
									if(BatchOrInt)		
									{	
										if(batch.hasNext())
										{
										input= batch.next();
										System.out.println(input);
										}
										else{
											logbook.error("No extra data");
											System.exit(-1);
										}
									}
									else 	input = userInput.next();
									cash = Float.parseFloat(input);
									if(cash < 0 ) throw new Exception();
									break;
								}
								catch(Exception IO){
									if(BatchOrInt)
									{
										System.out.println("Invalid cash");
									}
									else
									{
										System.out.printf("Please re-pay cash: ");
										continue;
									}
								}
						}
					}while(cash < totalMoney);	
				}
				}
				System.out.printf("Change $: ");
				float change = cash- totalMoney;
				formattedFloat = myFormat.format(change);
				System.out.println( formattedFloat);
				//after each success sale, the info will be recorded in the file.
				String success;
				if(NumOfSale <10)
				{
					success ="SalesID0"+NumOfSale+"     "+"total $ "+ totalMoney+"; ";
				}
				else success ="SalesID"+NumOfSale+"     "+"total $ "+ totalMoney+"; ";
				for ( int i = 0 ; i <purchasedList.plist.size();i++)
				{	
					
					success+= purchasedList.plist.get(i).getName()+" "+purchasedList.plist.get(i).howmany()+"; ";
				}
				logbook.record(success);
			}
		}
		mode();
	}

	void cancel() {
		int release=0;
		int position;
		for( int i =0;i<purchasedList.plist.size();i++)
		{
			position = products.isExist(purchasedList.plist.get(i).getKey());
			release = purchasedList.plist.get(i).howmany();
			products.plist.get(i).add(release);
		}
		if( NumOfSale < 10)
		logbook.error("SalesID0" + NumOfSale+" cancelled!");
		else logbook.error("SalesID" + NumOfSale+" cancelled!");
	}

	
}
